package no.awi.wpd.probability;

import java.math.BigDecimal;
import java.math.MathContext;

public class ProbabilityFunctions {

    /**
     * Given n choices, such as pizza toppings, and k 'slots', such as two pizza
     * toppings per pizza, the binomial coefficient will determine how many
     * non-ordered combinations exist, or how many different pizzas one can
     * order.
     * <p>
     * See <a href='http://en.wikipedia.org/wiki/Binomial_coefficient'>Wikipedia</a> for more.
     * 
     * @param n - number of choices
     * @param k - number of slots
     * @return number of combinations
     */
    public static BigDecimal binomialCoefficient(int n, int k) {
        if (n < 0 || k < 1 || n > k) {
            throw new IllegalArgumentException();
        }
        if (n == 0 || n == k) {
            return BigDecimal.valueOf(1);
        }
        int i = k;
        BigDecimal numerator = BigDecimal.valueOf(k);
        while (--i > n) {
            numerator = numerator.multiply(BigDecimal.valueOf(i), MathContext.UNLIMITED);
        }

        i = k - n;
        BigDecimal denominator = BigDecimal.valueOf(i);
        while (--i > 1) {
            denominator = denominator.multiply(BigDecimal.valueOf(i), MathContext.UNLIMITED);
        }
        BigDecimal result = numerator.divide(denominator, MathContext.UNLIMITED);
		return result;
    }

    public static double rerollOnFailure(double p) {
        return 1 - Math.pow(1 - p, 2);
    }
}
